/**
 * Copyright (C) 2013 Oleg Anastassov <oleg.anastassov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.loc.desktop.run;

import kz.kstu.loc.desktop.dialogs.AboutDialog;
import kz.kstu.loc.desktop.dialogs.ExtractDialog;
import kz.kstu.loc.desktop.dialogs.PatchDialog;
import kz.kstu.loc.desktop.icon.GUIFactory;
import kz.kstu.loc.desktop.icon.GUIIcon;
import kz.kstu.loc.util.GUIUtils;
import kz.kstu.loc.util.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

/**
 * Главное окно программы.
 * <p/>
 * Date: 16.01.2013
 * Time: 22:57
 *
 * @author Oleg Anastassov
 */
public class AppFrame extends JFrame {

    private static final String TITLE = "Локализатор";

    private static final int WIDTH = 600;
    private static final int HEIGHT = 400;

    private JMenuItem extractMenuItem;
    private JMenuItem patchMenuItem;
    private JMenuItem exitMenuItem;
    private JMenuItem aboutMenuItem;

    private JTextArea textArea;
    private JButton saveLogButton;
    private JButton clearLogButton;

    public AppFrame() {
        initWindow();
        initStaticComponents();
        initListeners();
        initAccelerators();
    }

    private void initWindow() {
        setIconImage(GUIFactory.getImage(GUIIcon.LOGO));
        setTitle(TITLE);
        setSize(new Dimension(WIDTH, HEIGHT));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    private void initStaticComponents() {
        setJMenuBar(getMainMenuBar());

        textArea = new JTextArea(getDescription());
        textArea.setEnabled(false);
        textArea.setLineWrap(true);
        JScrollPane scrollPane = new JScrollPane(
                textArea,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
        );
        add(scrollPane);

        // Нижняя панель для очистки и сохранения лога
        JPanel grid = new JPanel(new GridLayout(1, 2, 5, 0));
        saveLogButton = new JButton("Сохранить в файл");
        saveLogButton.setIcon(GUIFactory.getIcon(GUIIcon.SAVE));
        grid.add(saveLogButton);
        clearLogButton = new JButton("Очистить лог");
        clearLogButton.setIcon(GUIFactory.getIcon(GUIIcon.CLEAR));
        grid.add(clearLogButton);

        JPanel flow = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        flow.add(grid);
        // скрыть пока не будет вестись лог в textArea
        // add(flow, BorderLayout.SOUTH);

        Timer timer = new Timer(100, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                switchButtons(!textArea.getText().isEmpty());
            }
        });
        timer.start();
    }

    private void switchButtons(boolean enableFlag) {
        saveLogButton.setEnabled(enableFlag);
        clearLogButton.setEnabled(enableFlag);
    }

    private JMenuBar getMainMenuBar() {
        JMenuBar bar = new JMenuBar();

        // меню "Файл"
        JMenu fileMenu = new JMenu("Файл");
        fileMenu.setIcon(GUIFactory.getIcon(GUIIcon.FILE));
        extractMenuItem = new JMenuItem(
                "Извлечь...",
                GUIFactory.getIcon(GUIIcon.EXTRACT)
        );
        patchMenuItem = new JMenuItem(
                "Патч...",
                GUIFactory.getIcon(GUIIcon.PATCH)
        );
        exitMenuItem = new JMenuItem(
                "Выход",
                GUIFactory.getIcon(GUIIcon.EXIT)
        );
        fileMenu.add(extractMenuItem);
        fileMenu.add(patchMenuItem);
        fileMenu.addSeparator();
        fileMenu.add(exitMenuItem);
        bar.add(fileMenu);

        // меню "Помощь"
        JMenu helpMenu = new JMenu("Помощь");
        helpMenu.setIcon(GUIFactory.getIcon(GUIIcon.HELP));
        aboutMenuItem = new JMenuItem(
                "О программе..",
                GUIFactory.getIcon(GUIIcon.ABOUT)
        );
        helpMenu.add(aboutMenuItem);
        bar.add(helpMenu);
        return bar;
    }

    private void initListeners() {
        extractMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ExtractDialog dialog = new ExtractDialog();
                GUIUtils.centerAndShow(dialog);
            }
        });
        patchMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                PatchDialog dialog = new PatchDialog();
                GUIUtils.centerAndShow(dialog);
            }
        });
        exitMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        aboutMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                AboutDialog dialog = new AboutDialog();
                GUIUtils.centerAndShow(dialog);
            }
        });
        clearLogButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.setText(StringUtils.EMPTY_STRING);
            }
        });
    }

    private void initAccelerators() {
        extractMenuItem.setAccelerator(
                KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_MASK)
        );
        patchMenuItem.setAccelerator(
                KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK)
        );
        exitMenuItem.setAccelerator(
                KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_MASK)
        );
        aboutMenuItem.setAccelerator(
                KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)
        );
    }

    private String getDescription() {
        return "Инструмент предназначен для работы с локализируемыми ресурсами.\n\n" +
                "    - извлечение текстовых элементов из файлов ресурсов (*.orig; *.properties);\n" +
                "      (в качестве префикса используется символ '^')\n" +
                "    - экспорт в Microsoft Excel (*.xls);\n" +
                "    - импорт из Microsoft Excel (*.xls) для патча файлов текстовых ресурсов;";
    }

}
